package com.example.pubmedcrawler.service;

import com.example.pubmedcrawler.model.Literature;
import com.example.pubmedcrawler.model.SearchResult;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Service
public class PubMedCrawlerService {

    private static final String BASE_URL = "https://pubmed.ncbi.nlm.nih.gov";
    private static final String SEARCH_URL = BASE_URL + "/?term=%s&page=%d";
    private static final String DETAIL_URL = BASE_URL + "/%s/";

    public SearchResult search(String query, int page) throws IOException {
        List<Literature> literatures = new ArrayList<>();
        String url = String.format(SEARCH_URL, query, page);
        Document doc = Jsoup.connect(url).userAgent("Mozilla/5.0").get();

        Elements articles = doc.select("article.full-docsum");
        for (Element article : articles) {
            Literature literature = new Literature();

            // 提取基本信息
            literature.setTitle(article.select("a.docsum-title").text());
            literature.setAuthors("作者：" + article.select("span.docsum-authors").text());
            // 先不要期刊 
            // literature.setJournal("期刊：" + article.select("span.docsum-journal-citation").text());
            // literature.setJournal("xxx");

            // System.out.println("标题：" + article.select("a.docsum-title").text());
            // System.out.println("作者：" + article.select("span.docsum-authors").text());
            // System.out.println("期刊" + article.select("span.docsum-journal-citation").text());
            

            // 提取PMID（从标题链接中）
            Element titleLink = article.selectFirst("a.docsum-title");
            if (titleLink != null) {
                String href = titleLink.attr("href");
                // 从href中提取PMID，例如从"/35337650/"中提取"35337650"
                String pmid = href.replaceAll("/", "").trim();
                literature.setPmid(pmid);
                // System.out.println("PMID: " + pmid);
            }

            // 提取发表日期
            // String journalCitation = literature.getJournal();
            String journalCitation = article.select("span.docsum-journal-citation").text();
            if (journalCitation.contains(";")) {
                String datePart = journalCitation.split("; ")[0].trim();
                if (datePart.contains(". ")) {
                    int dotIndex = datePart.indexOf(". ");
                    if (dotIndex != -1 && dotIndex + 2 <= datePart.length()) {
                        datePart = datePart.substring(dotIndex + 2).trim();
                        literature.setPublicationDate("发表日期：" + datePart.split(";")[0]); // 只提取到月份

                    }
                }
                // System.out.println("发表日期：" + datePart.split(";")[0]);
            }

            // 提取摘要（从详情页）
            String detailUrl = String.format(DETAIL_URL, literature.getPmid());
            // System.out.println("详情页URL: " + detailUrl);
            Document detailDoc = Jsoup.connect(detailUrl).userAgent("Mozilla/5.0").get();
            Element abstractElement = detailDoc.selectFirst("div.abstract div");
            if (abstractElement != null) {
                literature.setAbstractText(abstractElement.text());
                // System.out.println("摘要：" + abstractElement.text());
            } 

            literatures.add(literature);
            // System.out.println("------------------");
        }


        // 提取总页数（假设每页20条结果）
        Element resultsSummary = doc.selectFirst("div.results-amount");
        int totalResults = 0;
        if (resultsSummary != null) {
            String summaryText = resultsSummary.text().replaceAll(",", "");
            totalResults = Integer.parseInt(summaryText.replaceAll("[^0-9]", ""));
        }
        // 限制总页数不超过实际可访问的最大页码
        int totalPages = (int) Math.ceil(totalResults / 20.0);
        // 增加安全检查，避免页码过大
        if (totalPages > 1000) {
            totalPages = 1000; // 设置合理的最大页码限制
        }
        return new SearchResult(literatures, totalPages);
    }
}